﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Web.SystemConfig.Services;
using Web.SystemConfig.DataAccess;
using System.Data;
using Microsoft.Web.UI.WebControls;
using System.Web.UI;
using DreamBuilder.Common;
using DreamBuilder.Core.Message;


namespace Web.SystemConfig.Business
{
    public class BUSAuth_Role : BusinessBase, IAuth_Role
    {
        DALAuth_Role dal;

        public BUSAuth_Role()
        {
            dal = new DALAuth_Role();
        }


        private DataTable dtAuth;

        public DataTable DtAuth
        {
            get
            {
                if (dtAuth == null)
                {
                    dtAuth = dal.GetAllMenuData();
                }
                return dtAuth;
            }
        }

        private DataTable dtFuncs;

        public DataTable DtFuncs
        {
            get
            {
                if (dtFuncs == null)
                {
                    dtFuncs = dal.GetAllFunctionData();
                }
                return dtFuncs;
            }
        }

        public void LoadTree(Microsoft.Web.UI.WebControls.TreeView tree)
        {
            tree.Nodes.Clear();
            if (DtAuth != null && DtAuth.Rows.Count > 0)
            {
                DataRow[] arrDr = DtAuth.Select("Parent_Menu_ID is null ");
                if (arrDr == null || arrDr.Length == 0)
                {
                    return;
                }
                else
                {
                    DataRow rootDr = arrDr[0];
                    TreeNode root = new TreeNode();
                    root.ID = rootDr["Menu_ID"].ToString();
                    root.Text = CResManager.GetPublicString("Menus", root.ID);
                    tree.Nodes.Add(root);
                    root.CheckBox = true;
                    root.Expanded = true;
                    AddChildNode(root, rootDr["Menu_ID"].ToString());
                }
            }
        }


        private void AddChildNode(TreeNode root, string parentID)
        {
            if (DtAuth != null && DtAuth.Rows.Count > 0)
            {
                DataRow[] arrDr = DtAuth.Select("Parent_Menu_ID='" + parentID + "'");
                if (arrDr == null || arrDr.Length == 0)
                {
                    return;
                }
                foreach (DataRow dr in arrDr)
                {
                    TreeNode child = new TreeNode();
                    child.ID = dr["Menu_ID"].ToString();
                    child.Text = CResManager.GetPublicString("Modules", child.ID);
                    root.Nodes.Add(child);
                    child.CheckBox = true;
                    child.Expanded = true;
                    AddChildNode(child, dr["Menu_ID"].ToString());

                    if (IsLeafMenu(child.ID))
                    {
                        child.Expanded = false;
                        DataRow[] arrDrFuncs = DtFuncs.Select("Menu_ID='" + dr["Menu_ID"].ToString() + "'");
                        if (arrDrFuncs == null || arrDrFuncs.Length == 0)
                        {
                            continue;
                        }
                        foreach (DataRow drFunc in arrDrFuncs)
                        {
                            TreeNode FuncNode = new TreeNode();
                            FuncNode.ID = drFunc["Func_ID"].ToString();
                            FuncNode.NodeData = "Function";
                            FuncNode.Text = CResManager.GetPublicString("FunctionTypes", drFunc["Func_Name_ID"].ToString());
                            FuncNode.CheckBox = true;
                            child.Nodes.Add(FuncNode);
                        }
                    }
                }
            }
        }

        private bool IsLeafMenu(string moduleID)
        {
            DataRow[] arrDr = DtAuth.Select(" Parent_Menu_ID = '" + moduleID + "' ");
            if (arrDr.Length > 0)
            {
                return false;
            }
            else
            {
                return true;
            }
        }


        /// <summary>
        /// 根据数据设置角色树的初始值
        /// </summary>
        /// <param name="tree"></param>
        /// <param name="Role_ID"></param>
        public void SetInitFuncValue(Microsoft.Web.UI.WebControls.TreeView tree, string Role_ID)
        {
            DataTable dtRole_Function = dal.GetFunctionByRoleID(Role_ID);
            if (dtRole_Function == null || dtRole_Function.Rows.Count == 0)
            {
                return;
            }
            //遍历第一层子节点
            foreach (DataRow dr in dtRole_Function.Rows)
            {
                foreach (TreeNode tn in tree.Nodes)
                {
                    //如果找到该节点,选中,并结束本次循环
                    if (tn.ID == dr["Func_ID"].ToString())
                    {
                        tn.Checked = true;
                        SetParentNodeChecked(tn);
                        continue;
                    }
                    //如果未找到,则找子节点中是否有
                    if (SetChildValue(tn, dr["Func_ID"].ToString()))
                    {
                        continue;
                    }
                    //否则,继续找其他节点
                }
            }
        }

        private bool SetChildValue(TreeNode tn, string Func_ID)
        {
            foreach (TreeNode tnChild in tn.Nodes)
            {
                if (tnChild.ID == Func_ID)
                {
                    tnChild.Checked = true;
                    SetParentNodeChecked(tnChild);
                    return true;
                }
                if (SetChildValue(tnChild, Func_ID))
                {
                    return true;
                }
            }
            return false;
        }

        private void SetParentNodeChecked(TreeNode tn)
        {
            TreeNode parent = tn.Parent as TreeNode;
            while (parent != null)
            {
                parent.Checked = true;
                parent = parent.Parent as TreeNode;
            }
        }


        public ResultInfo SaveEditDataAndTreeData(System.Data.DataSet dsInfo, Microsoft.Web.UI.WebControls.TreeView treeView)
        {
            ResultInfo result = base.Save(dsInfo);
            if (result.bSuccess == false)
            {
                return result;
            }
            try
            {
                string roleID = dsInfo.Tables[0].Rows[0]["P_Auth_Role.Role_ID"].ToString();
                dal.DeleteOldFuncData(roleID);

                List<string> listFunc_ID = new List<string>();
                foreach (TreeNode tn in treeView.Nodes)
                {
                    if (tn.NodeData == "Function" && tn.Checked == true)
                    {
                        listFunc_ID.Add(tn.ID);
                    }
                    GetChildFuncID(tn, listFunc_ID);
                }
                dal.SaveFuncs(listFunc_ID, roleID);
            }
            catch (System.Data.SqlClient.SqlException sqlErr)
            {
                result.bSuccess = false;
                result.ErrorID = sqlErr.Number.ToString();
            }
            catch (System.Exception err)
            {
                result.bSuccess = false;
                result.ErrorDesc = err.Message;
            }
            return result;
        }

        private void GetChildFuncID(TreeNode tn, List<string> listFunc_ID)
        {
            foreach (TreeNode tnChild in tn.Nodes)
            {
                if (tnChild.NodeData == "Function" && tnChild.Checked == true)
                {
                    listFunc_ID.Add(tnChild.ID);
                }
                GetChildFuncID(tnChild, listFunc_ID);
            }
        }

        public DataSet GetDeleteChildInfo(string pkValue)
        {
            return dal.GetDeleteChildInfo(pkValue);
        }
        #region add by 刘英男 检查用户角色名是否唯一
        /// <summary>
        ///  检查用户角色名是否唯一
        /// </summary>
        /// <param name="roleid">角色名</param>
        /// <returns>是，否</returns>
        public bool CheckRoleName(string rolename)
        {
            int userroleid = dal.CheckRoleName(rolename);
            if (userroleid == 0)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        #endregion
        #region add by 刘英男 检查用户主键是否唯一
        /// <summary>
        ///  检查用户主键是否唯一
        /// </summary>
        /// <param name="userCheckID">用户登录id</param>
        /// <returns>是,否</returns>
        public bool CheckRolePrimary(string RoleCheckID)
        {
            int userroleid = dal.CheckRolePrimary(RoleCheckID);
            if (userroleid == 0)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        #endregion
        //by lyn 20111019
        public void ModifyRole(string userName, DateTime userTime, string mainKey)
        {
            dal.ModifyRoleInfo(userName, userTime, mainKey);
        }
        #region add by 刘英男 20111102 角色名称
        /// <summary>
        /// 根据主键获取角色名称
        /// </summary>
        /// <param name="pkValue">主键</param>
        /// <returns>pkName</returns>
        public String GetpkNameByRolepkValue(string pkValue)
        {
            string pkName = dal.GetpkNameByRolepkValueInfo(pkValue);
            return pkName;
        }
        #endregion


        public bool IsThisRole(string userID, string roleID)
        {
            return dal.IsThisRole(userID, roleID);
        }
    }
}
